<?php

use Mapper\MemberModel as MemberMapper;
use Mapper\MemberAvatarModel as MemberAvatarMapper;

class MemberController extends \Base\ApiController {

    /**
     * @desc 绑定手机号
     *
     * @return false
     */
    public function bindmobileAction() {
        $request = $this->getRequest();
        $mobile  = (string)$request->get('mobile');
        $code    = (string)$request->get('code');
        $uid     = $this->getSession()->get('Uid');
        $uid     = $uid['uid'];

        if(empty($mobile)) {
            return $this->response(null, false, 30100, '手机号码不能为空');
        }

        if(empty($code)) {
            return $this->response(null, false, 30101, '验证码不能为空,请重新输入');
        }

        if(!\Lib\Is::mobileNum($mobile)) {
            return $this->response(null, false, 30102, '手机号码格式有误');
        }

        $verifyCode = \Lib\Msgcode::verify($mobile, 'bindmobile', $code);

        if(!$verifyCode) {
            return $this->response(null, false, 30103, '验证码有误');
        }

        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findByMobile($mobile);

        if($memberModel instanceof \MemberModel) {
            return $this->response(null, false, 30104, '手机号已被绑定, 请更换手机号');
        }

        $data = [
            'mobile' => $mobile,
        ];

        try {
            $rows = $memberMapper->update($data, ['id' => $uid]);
            return $rows > 0 ? $this->response(null) : $this->response(null, false, 10121, '绑定手机号失败');
        } catch(\Exception $e) {
            return $this->response(null, false, 10100, '异常信息报错');
        }
    }

    /**
     * @desc 发生注册短信验证码
     *
     * @return false
     */
    public function sendmsgAction() {
        $request = $this->getRequest();
        $mobile  = (string)$request->get('mobile');

        if(empty($mobile)) {
            return $this->response(null, false, 30100, '手机号码不能为空');
        }

        if(!\Lib\Is::mobileNum($mobile)) {
            return $this->response(null, false, 30102, '手机号码格式错误');
        }

        $code = \Lib\Msgcode::create($mobile, 'bindmobile');

        \Lib\Queue::push('sms', [
            'mobile'  => $mobile,
            'content' => $code,
        ]);

        return $this->response('短信已发送!');
    }

    /**
     * @desc 完善用户资料
     *
     * @return false
     */
    public function editinfoAction() {
        $request  = $this->getRequest();
        $uid      = $this->uid();
        $nickName = (string)$request->get('nick_name');
        $mainGame = (string)$request->get('main_game');
        $birthday = (string)$request->get('birthday');
        $avatars  = $request->get('avatar');

        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($uid);
        $avatarMapper = MemberAvatarMapper::getInstance();

        if(!$memberModel instanceof \MemberModel) {
            return $this->response(null, false, 10110, 'Invalid Uid');
        }

        if(!empty($nickName)) {
            $memberModel->setNick_name(urlencode($nickName));
            $memberModel->setLetter(\Lib\Pinyin::to_first($nickName));
        }

        if(!empty($mainGame)) {
            $memberModel->setMain_game($mainGame);
        }

        $birthday = strtotime($birthday);

        if(!empty($birthday)) {
            $memberModel->setBirthday($birthday);
        }

        if(!empty($avatars[0])) {
            $memberModel->setAvatar($avatars[0]);
        }

        $memberMapper->begin();

        if(is_array($avatars) && $avatarMapper->saveAvatar($uid, $avatars) === true) {
            try {
                $memberMapper->update($memberModel, ['id' => $uid]);
                $rows = 1;
            } catch(\Exception $exc) {
                $rows = 0;
            }

            if($rows > 0) {
                $memberMapper->commit();

                return $this->response(null);
            }
        }

        $memberMapper->rollback();

        return $this->response(null, false, 10121, '资料更新失败');
    }

    /**
     * @desc 取得用户信息
     *
     * @return false
     */
    public function myinfoAction() {
        $uid          = $this->uid();
        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($uid);
        $avatarMapper = MemberAvatarMapper::getInstance();

        if(!$memberModel instanceof \MemberModel) {
            return $this->response(null, false, 10110, 'Invalid Uid');
        }

        $birthday = empty($memberModel->getBirthday()) ? '' : date('Y-m-d', $memberModel->getBirthday());

        $return = [
            'avatar'    => array_values($avatarMapper->avatars($uid)),
            'nick_name' => urldecode($memberModel->getNick_name()),
            'gender'    => $memberModel->getGender(),
            'main_game' => $memberModel->getMain_game(),
            'birthday'  => $birthday,
        ];

        return $this->response($return);
    }

    public function loginAction() {
        $host = \Lib\Wechat::getInstance()->login();
        $this->redirect($host);
        return false;
    }

    public function oauthAction() {
        $oauthObj = \Lib\Wechat::getInstance()->oauth();
        $openId   = $oauthObj->openid;

        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findByOpen_id($openId);

        if($memberModel instanceof \MemberModel) {
            $this->getSession()->set('Uid', ['uid' => $memberModel->getId()]);
            $redirect = $this->getSession()->get('Referer');
            if(empty($redirect)) {
                $this->redirect('http://wx.dev.gaoqiapp.com/');
            } else {
                $this->redirect($redirect);
                $this->getSession()->del('Referer');
            }

            return false;
        }

        $userObj = \Lib\Wechat::getInstance()->user($openId, $oauthObj->access_token);

        $nickname = isset($userObj->nickname) ? $userObj->nickname : '';
        $gender   = isset($userObj->sex) ? $userObj->sex : 0;
        $avatar   = isset($userObj->headimgurl) ? $userObj->headimgurl : '';

        $memberModel = new \MemberModel();
        $memberModel->setNick_name(urlencode($nickname));
        $memberModel->setGender($gender);
        $memberModel->setAvatar($avatar);
        $memberModel->setOpen_id($openId);
        $memberModel->setStatus(\Lib\Consts::LOGIN_STATUS_NORMAL);
        $memberModel->setRegist_time(time());

        try {
            $lastId = $memberMapper->insert($memberModel);

            if($lastId > 0) {
                $this->getSession()->set('Uid', ['uid' => $memberModel->getId()]);
                $this->redirect('http://wx.dev.gaoqiapp.com/');
//                $this->redirect($this->getSession()->get('Referer'));
//                $this->getSession()->del('Referer');
//                return $this->response(null);
                return false;
            } else {
                return $this->response(null, false, 10121, '注册失败');
            }

        } catch(\Exception $e) {
            return $this->response(null, false, 10100, '异常信息报错');
        }
    }

}
